/*
 * @Author: Komens
 * @Date: 2022-01-21 14:00:00
 * @LastEditTime: 2022-01-21 18:02:58
 * @LastEditors: Komens
 */

const path = require("path");
const fs = require("fs");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const Webpack = require("webpack");

/**
 * 读取pages目录
 * 拿到所有的页面
 */
const excludesDir = ["assets"]; // 排除的文件夹
const pages = getPages();

const entry = {};
const defaultPlugins = [];
pages.forEach((page) => {
  entry[page] = `./pages/${page}/index.js`;
  defaultPlugins.push(
    new HtmlWebpackPlugin({
      filename: `${page}/index.html`,
      template: `./pages/${page}/index.html`, //使用模板index.html
      chunks: [page], //index.html里引用打包生成的index.js
      inject: "head",
    })
  );
});

module.exports = {
  mode: "development",
  entry: entry,
  output: {
    filename: "[name]/index.[chunkhash].js",
    path: path.resolve(__dirname, "./.cache"),
    clean: {
      keep: /assets/,
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader", //es6+转换es5
        },
      },
      {
        test: /\.css$/, //sass/scss转换css
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /\.s[ac]ss$/, //sass/scss转换css
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
  plugins: [
    // new CleanWebpackPlugin({
    //   cleanOnceBeforeBuildPatterns: ["**/*", "!favicon.ico", "!assets/**"],
    // }),
    ...defaultPlugins,
    new MiniCssExtractPlugin({
      filename: "[name]/index.[contenthash].css",
    }),
    new CopyPlugin({
      patterns: [{ from: "pages/assets", to: "assets" }],
    }),
    new Webpack.ProvidePlugin({
      //全局引入jquery，此后在任何位置可直接使用$，Lodash或其他库也可以像这样引入，当然也可以在dist目录的lib文件夹下放第三方库，在html模板中直接引入
      $: "jquery",
    }),
  ],
};

function getPages() {
  const res = fs.readdirSync(path.join(__dirname, "pages"));
  const excludesDirMap = {};
  excludesDir.forEach((dir) => {
    excludesDirMap[dir] = true;
  });
  const dirs = [];
  res.forEach((dir) => {
    if (!excludesDirMap[dir]) {
      dirs.push(dir);
    }
  });

  return dirs;
}
